import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Modal,
  Row,
  Col,
  Select,
  Input,
  Button,
  Table,
} from 'antd';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { GardenListParams } from '../data';

const { Option } = Select;

interface SaveGardenListProps extends FormComponentProps {
  saveVisible: boolean;
  gardenInfo?: any;
  INITINFO?: any;
  dispatch?: Dispatch;
  searchGarden: (saveVisible: boolean, row?: any) => void;
}

interface SaveGardenListState {
  searchValues: GardenListParams;
}

@connect(({
  postManagementAdd: { gardenInfo },
  common: { INITINFO },
}: any) => ({ gardenInfo, INITINFO }))

class SaveGardenListElem extends Component<SaveGardenListProps, SaveGardenListState> {
  state = {
    searchValues: {
      pareaCode: '',
      name: '',
      type: '',
      propertyId: '',
      pageIndex: 1,
      pageSize: 10,
    },
  }

  columns = [
    { title: '小区', dataIndex: 'name' },
    {
      title: '物业公司',
      dataIndex: 'propertyName',
      render: (val: string) => {
        let value = '';
        if (val && val.length > 8) value = `${val.substring(0, 8)}...`;
        else value = val;
        return <span title={val}>{value}</span>;
      },
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      render: (val: string) => {
        let value = '';
        if (val && val.length > 18) value = `${val.substring(0, 18)}...`;
        else value = val;
        return <span title={val}>{value}</span>;
      },
    },
    {
      title: '场景',
      dataIndex: 'type',
      render: (val: number) => {
        const { INITINFO: { gardenType } } = this.props;
        let typeName = '';
        gardenType.map((item: any) => {
          if (item.mCode === val) typeName = item.codeName;
          return null;
        });
        return typeName;
      },
    },
    {
      title: '操作',
      render: (val: number, row: any) => (
        <span
          className="operLink"
          onClick={() => this.handleSubmit(row)}
        >选择
        </span>
      ),
    },
  ]

  componentDidMount() {
    this.fetchAction('common/fetchAllProperty');
    this.fetchAction('common/fetchAreaList');
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { searchValues } = this.state;
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      const params = {
        ...searchValues,
        ...values,
        pageIndex: 1,
        pageSize: 10,
      };
      this.setState({
        searchValues: params,
      }, () => this.fetchAction('fetchGarden', params));
    });
  }

  handleSubmit = (row: any) => {
    const { searchGarden } = this.props;
    searchGarden(false, row);
  }

  handleCancel = () => {
    const { searchGarden } = this.props;
    searchGarden(false);
    this.setState({
      searchValues: {
        pareaCode: '',
        name: '',
        type: '',
        propertyId: '',
        pageIndex: 1,
        pageSize: 10,
      },
    });
  }

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    this.setState({
      searchValues: params,
    }, () => this.fetchAction('fetchGarden', params));
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch }: any = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `postManagementAdd/${typeName}`;
    dispatch({ type, payload });
  }

  render() {
    const { searchValues: { pageIndex, pageSize } } = this.state;
    const {
      saveVisible,
      gardenInfo,
      INITINFO: { allPropertyList, gardenType, areaList },
      form: { getFieldDecorator },
    } = this.props;

    const dataSource = gardenInfo ? gardenInfo.list : [];
    const pagination: object = gardenInfo
      ? {
        total: gardenInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      } : {};

    return (
      <Modal
        title="选择小区"
        width={800}
        visible={saveVisible}
        destroyOnClose
        onOk={this.handleSubmit}
        onCancel={this.handleCancel}
      >
        <Form className="tableListForm marginB20" onSubmit={this.handleSearch}>
          <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
            <Col md={10} sm={24}>
              <Form.Item label="物业公司" colon={false}>
                {getFieldDecorator('propertyId')(
                  <Select
                    showSearch
                    placeholder="请选择"
                    filterOption={(input: any, option: any) => (
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    )}
                  >
                    {allPropertyList.map((item: any) => (
                      <Option value={item.id} key={item.id}>{item.name}</Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col md={10} sm={24}>
              <Form.Item label="　　小区" colon={false}>
                {getFieldDecorator('name')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
            <Col md={10} sm={24}>
              <Form.Item label="　　场景" colon={false}>
                {getFieldDecorator('type')(
                  <Select placeholder="请选择">
                    {gardenType.map((item: any) => (
                      <Option value={item.mCode} key={item.mCode}>{item.codeName}</Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col md={10} sm={24}>
              <Form.Item label="　　省份" colon={false}>
                {getFieldDecorator('pareaCode')(
                  <Select placeholder="请选择">
                    {areaList.map((item: any) => (
                      <Option value={item.code} key={item.id}>{item.name}</Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col md={4} sm={24}>
              <div className="flexFeView">
                <Button
                  type="primary"
                  size="small"
                  htmlType="submit"
                  className="smallButton"
                >
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
        <Table
          rowKey="id"
          className="tableList statementTable"
          columns={this.columns}
          dataSource={dataSource}
          pagination={pagination}
        />
      </Modal>
    );
  }
}

export default Form.create<SaveGardenListProps>()(SaveGardenListElem);
